package com.ly.mp.busicen.rule.flow.action.plugin.function;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.ly.mp.busicen.rule.XruleStrUtils;
import com.ly.mp.busicen.rule.flow.FlowSpelUtil;
import com.ly.mp.busicen.rule.flow.IDataVolume;
import com.ly.mp.busicen.rule.flow.action.ActionException;
import com.ly.mp.busicen.rule.flow.action.IAction;
import com.ly.mp.busicen.rule.flow.action.plugin.ActionFunctionContainer;
import com.ly.mp.busicen.rule.flow.action.plugin.IActionFuncRegister;
import com.ly.mp.busicen.rule.flow.action.plugin.IFuncResult;

@Component
public class ActionExecuteFunctionExtention implements IActionFuncRegister {
	

	@Override
	public void actionFuncRegist(ActionFunctionContainer container) {
		container.regist("function_excelhead", this::excelHeaderConvert);
		container.regist("function_blank", this::blank);
	}
	
	IFuncResult blank(IAction action,IDataVolume dataVolume,String[] params) {	
		return IFuncResult.defaults();
	}
	
	/**
	 * excel表头 转换 中文转英文
	 * @param action
	 * @param dataVolume
	 * @param params
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	IFuncResult excelHeaderConvert(IAction action,IDataVolume dataVolume,String[] params) {		
		Object excelData = FlowSpelUtil.spelGetData(action, action.extKey());
		if (excelData!=null) {
			if (excelData instanceof List) {
				List excelList = (List) excelData;
				if (!excelList.isEmpty()) {
					Map<String, String> kv = XruleStrUtils.splitParam(XruleStrUtils.splitXKH(action.content()));
					if (kv==null) {
						throw new ActionException("未配置excel表头转换内容");
					}
					for (Object ed : excelList) {
						if (ed!=null&&ed instanceof Map) {
							Map data = (Map)ed;
							kv.forEach((k,v)->{
								data.put(v, data.get(k));
								data.remove(k);
							});
						}else {
							throw new ActionException("传入的excel数据不能为null且类型必须为Map");
						}
					}
				}
			}else {
				throw new ActionException("传入的excel数据为null");
			}
		}		
		return IFuncResult.defaults();
	}	
}
